package com.zy.explore.common.infrastructure.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * description Lambda工具类
 *
 * @author ChinaYin  主页:https://gitee.com/zy-explorej2ee 邮箱:zyexplorej2ee@sina.com
 * @date 2021年07月07日 15:27
 */
public class LambdaUtil {

    /**
     * 函数式接口 T -> bollean
     * @param keyExtractor
     * @param
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap map = new ConcurrentHashMap<>(16);
        return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE) == null;
        // 这个也可以，不过感觉效率要低一些，线程不是那么安全
        // Set seen = ConcurrentHashMap.newKeySet();
        // return t -> seen.add(keyExtractor.apply(t));
    }
}
